<template>
  <div ref="container" class="three-container"></div>
</template>

<script>
import * as THREE from 'three';
import { CSS3DRenderer, CSS3DSprite } from 'three/examples/jsm/renderers/CSS3DRenderer.js';

export default {
  name: 'ThreeScene',
  mounted() {
    this.initThree();
  },
  methods: {
    initThree() {
      // 创建场景、相机和渲染器
      const scene = new THREE.Scene();
      const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      this.$refs.container.appendChild(renderer.domElement);

      // 创建 CSS3DRenderer
      const cssRenderer = new CSS3DRenderer();
      cssRenderer.setSize(window.innerWidth, window.innerHeight);
      cssRenderer.domElement.style.position = 'absolute';
      cssRenderer.domElement.style.top = '0';
      this.$refs.container.appendChild(cssRenderer.domElement);

      // 创建 CSS3DSprite
      const element = document.createElement('div');
      element.innerHTML = "Click me!";
      element.style.cursor = 'pointer';
      element.style.width = '100px';
      element.style.height = '50px';
      element.style.backgroundColor = 'rgba(255, 0, 0, 0.7)';
      element.style.textAlign = 'center';
      element.style.lineHeight = '50px'; // 垂直居中
      element.style.color = '#fff';

      const css3dSprite = new CSS3DSprite(element);
      css3dSprite.position.set(0, 0, 0); // 设置位置
      css3dSprite.scale.set();
      scene.add(css3dSprite);

      // 添加点击事件
      element.addEventListener('click', () => {
        alert('Sprite clicked!');
      });

      // 设置相机位置
      camera.position.z = 5;

      // 渲染循环
      const animate = () => {
        requestAnimationFrame(animate);
        cssRenderer.render(scene, camera);
        renderer.render(scene, camera);
      };
      animate();

      // 窗口调整大小处理
      window.addEventListener('resize', () => {
        const width = window.innerWidth;
        const height = window.innerHeight;
        renderer.setSize(width, height);
        cssRenderer.setSize(width, height);
        camera.aspect = width / height;
        camera.updateProjectionMatrix();
      });
    },
  },
};
</script>

<style scoped>
.three-container {
  position: relative;
  width: 100%;
  height: 100vh; /* 使容器占满整个视口 */
}
</style>
